/* 
 * File:   World.cpp
 * Author: nrechten
 * 
 * Created on 18 April 2011, 16:32
 *
 * The world class and subclass allow the server load the world from storage,
 * or in the case of the dummy world generate cells on the fly
 *
 */

#include "TerrainDatasource.h"
#include "Terrain.h"
#include "SceneModel.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

TerrainDatasource::TerrainDatasource() {
}

TerrainDatasource::~TerrainDatasource() {
}

DummyTerrainDatasource::DummyTerrainDatasource() {
    ground_level[0] = 5; //X
    ground_level[1] = 1; //Y
    ground_level[2] = 5; //Z
    ground_level[3] = 5; //X
    ground_level[4] = 1; //Y
    ground_level[5] = 5; //Z
    ground_level[6] = 5; //X
    ground_level[7] = 1; //Y
    ground_level[8] = 5; //Z
    ground_level[9] = 0; //X
    ground_level[10] = 0; //Y
    ground_level[11] = 0; //Z
    ground_level[12] = 5; //X
    ground_level[13] = 0; //Y
    ground_level[14] = 0; //Z
    ground_level[15] = 5; //X
    ground_level[16] = 1; //Y
    ground_level[17] = 1; //Z
    ground_level[18] = 5; //X
    ground_level[19] = 1; //Y
    ground_level[20] = 0; //Z

}

DummyTerrainDatasource::~DummyTerrainDatasource() {

}

Block* DummyTerrainDatasource::load_block(UNIT* coord, UNIT coord_depth, UNIT lod) {
    Cell* c = new Cell(coord_depth, null);
    if (_is_underground(coord, coord_depth)) {
        c->terrain_def_id = 1;
    } else {
        c->terrain_def_id = 0;
    }

    return c;
}

bool DummyTerrainDatasource::_is_underground(UNIT* coord, UNIT coord_depth) {
    for (int i = 0; i < coord_depth + 1; i++) {
        if (i == 6) {
            UNIT r = _rand(coord + i * 3);
            if (coord[i * 3 + 1] < r) {//ground_level[i*3+1]){
                return true;
            }
            if (coord[i * 3 + 1] > r) {//ground_level[i*3+1]){
                return false;
            }
        } else {
            //UNIT r = _rand(coord + i * 3);
            if (coord[i * 3 + 1] < ground_level[i*3+1]){
                return true;
            }
            if (coord[i * 3 + 1] > ground_level[i*3+1]){
                return false;
            }
        }

    }
    return false;
}

UNIT DummyTerrainDatasource::_rand(UNIT* coord) {
    //srand(coord[0] + coord[3]*10);
    return 10*sin(coord[0] + coord[2]*10);
}